/**
 * 
 */
ProfileEditPortlet = ProfileInformationPortlet.extend({
	init: function()	{
		this._super();
		this.name = 'ProfileEditPortlet';
		var usedId = 0;
	},
	
	processNode: function(node)	{
		this.renderPlaceholder(node);
	},
	
	renderPlaceholder: function(current)	{
		this.subject.notifyEvent('RenderPlaceholder', {'node': current, 'callback': 'RenderingDone', 'id': this.name, 'state':'Edit'});
	},
	
	finishRendering: function()	{
		this.subject.notifyEvent('DisplayRemainingNodes', {'id': this.name});
		this._super();
		this.subject.notifyEvent("HideProfileChildren");
		this.subject.notifyEvent("ProfileInputBindEvent");
		var eventData = {};
		eventData.placeholder = this.requestForEffectiveResource('TabPlaceholder');
		eventData.tabs = Array();
		var tabCandidates = this.requestForMatchingEffectiveResource('ProfileMainContent', 'div.Heading_container[rootname]');
		$(tabCandidates).each(function (index, value)	{
			var tabCandidate = {};
			var heading = $(value).find('h2 span');
			tabCandidate.title = $(heading).html();
			//console.log(tabCandidate.title);
			if (tabCandidate.title != '')	{
				tabCandidate.id = $(value).attr('id');
				$(heading).parent().hide();
				eventData.tabs.push(tabCandidate);
			}
		});
		this.subject.notifyEvent("RenderProfileEditTab", eventData);
	},
	
	onMockupPlaceholderKeyup: function(eventData)	{
//		var target = eventData.target;
//		if ($(target).attr('modified') != 'true')
//			return;
//		if ($(target).val() != "" && $(target).attr('binded') == undefined)	{
//			var ancestor = $(target).parents('div[mockup="true"]:first').parent();
//			ancestor.siblings('.children_container').show();
//			ancestor.parent().attr('id', $(ancestor).attr('id')+this.usedId);
//			$(target).attr('binded', 'true');
//			this.appendNewNode(target);
//		}
	},
	
	appendNewNode: function(target)	{
		//find the nearest ancestor which contains a rootname attribute
		var ancestor = $(target).parent().parent().parent().parent().parent();
		var name = $(ancestor).attr('rootname');
		this.subject.notifyEvent('BuildMockupNode', {'id': this.name, 'nodeName': name, 'nodeBefore': ancestor});
		
		//call the finishRendering hook
		this.finishRendering();
	},
	
	onProfileEditSaveProfile: function(eventData)	{
		var root = this.requestForEffectiveResource('ProfileMainContent');
		var subject = SingletonFactory.getInstance(Subject);
		var obj = this;
		obj.requestForEffectiveResource('SaveSuccess').html('');
		obj.requestForEffectiveResource('SaveError').html('');
		subject.notifyEvent('SaveProfile', {root: root, 
			success: function() {
				var subject = SingletonFactory.getInstance(Subject);
				subject.notifyEvent('NotifyGlobal', 'Bạn đã cập nhật thành công');
				subject.notifyEvent('RequestRoute', new Request('User'));
			},
			failure: function()	{
				var successMsg = obj.getLocalizedText('SaveError');
				obj.requestForEffectiveResource('SaveError').html(successMsg);
			}
		});
	},
	
	buildSavingData: function(prop_key, prop_val, parent_key)	{
		var partial = {};
		partial.prop_key = prop_key;
		partial.prop_val = prop_val;
		partial.parent_key = parent_key;
		return partial;
	}
});

ProfileEditPlugin = Class.extend({
	init: function()	{
		this.name = "ProfileEditPlugin";
	},
	
	onSaveProfile: function(eventData)	{
		var root = eventData.root;
		var success = eventData.success;
		var failure = eventData.failure;
		
		var dataToSent = {};
		dataToSent.data = Array();
		var obj = this;
		$(root).find('.profileData').each(function(index, value)	{
			var ancestor = $(value).parents('[rootname]:first');
			var prop_key = $(ancestor).attr('oid');
			if (prop_key == undefined || prop_key == '' || isNaN(prop_key))
				prop_key = $(ancestor).attr('rootname');
			var ancestorParent = $(ancestor).parents('[rootname]:first');
			var parent_key = $(ancestorParent).attr('oid');
			if (parent_key == undefined || parent_key == '' || isNaN(parent_key))
				parent_key = $(ancestorParent).attr('rootname');
			
			var formatter = $(value).attr('formatter');
			var prop_val = "";
			if (formatter == 'Normal' || formatter == 'NormalLarge')	{
				if ($(value).attr('modified') == 'true')	{
					prop_val = $(value).val();
					var partial = obj.buildSavingData(prop_key, prop_val, parent_key);
					dataToSent.data.push(partial);
				}
				return;
			} else if (formatter == 'Date')	{
				prop_val = $(value).val();
				var pattern=/\d\d,\s\w+\s\d\d\d\d/g;
				if (!prop_val.match(pattern))	{
					prop_val = '';
				}
			} else if (formatter == 'Enum')	{
				prop_val = $(value).find('input:checked').attr('value');
				if (prop_val == undefined)	{
					prop_val = '';
				}
			} else if (formatter == 'List' || formatter == 'Email' )	{
				var listData = Array();
				$(value).find('label.lblToken').each(function(i, v)	{
					var val = $(v).html();
					prop_key = $(v).attr('oid');
					var partial = obj.buildSavingData(prop_key, val, parent_key);
					dataToSent.data.push(partial);
				});
				return;
			}
			var partial = obj.buildSavingData(prop_key, prop_val, parent_key);
			dataToSent.data.push(partial);
		});
		dataToSent.data = $.toJSON(dataToSent.data);
		//console.log(dataToSent);
		this.onAjax('ajax', 'commit-profile', {'data': dataToSent.data}, 'POST', 
			{'onSuccess': function(ret)	{
				success();
			},
			'onFailure': function(message)	{
				failure();
			}
		});
	},
	
	buildSavingData: function(prop_key, prop_val, parent_key)	{
		var partial = {};
		partial.prop_key = prop_key;
		partial.prop_val = prop_val;
		partial.parent_key = parent_key;
		return partial;
	},
	
	onHideProfileChildren: function(eventData)	{
		$('.children_container').each(function(index, value)	{
			var id = $(value).parent().attr('id');
			if (id.match("AddNew$"))	{
				//parent is mockup?
				$(value).hide();
			}
		});
	},
	
	onProfileInputBindEvent: function(eventData)	{
		$('div[mockup="true"] input.profileData').bind('blur', function(event)	{
			generateEvent('MockupInputBlur', event);
			generateEvent('MockupPlaceholderKeyup', event);
		});
		
		$('.normal-formatter input.profileData,.normal-large-formatter textarea.profileData').bind('change', function(event)	{
			generateEvent('NormalInputChange', event);
		});
		
		$('div[mockup="true"] input.profileData').bind('focus', function(event)	{
			generateEvent('MockupInputFocus', event);
		});
	},
	
	onNormalInputChange: function(eventData)	{
		var target = eventData.target;
		$(target).attr('modified', 'true');
	},
	
	onMockupInputBlur: function(eventData)	{
		var target = eventData.target;
		if ($(target).val() == '')
			$(target).attr('modified', '');
		if ($(target).attr('modified') == 'true')
			return;
		$(target).val($(target).attr('oldVal'));
	},
	
	onMockupInputFocus: function(eventData)	{
		var target = eventData.target;
		if ($(target).attr('modified') == 'true')	{
			return;
		}
		if ($(target).val() != '')
			$(target).attr('oldval', $(target).val());
		$(target).val('');
	}
}).implement(PluginInterface).implement(AjaxInterface);